package com.ruben;

import com.ruben.annotation.BeanFieldSort;
import com.ruben.pojo.UserInfo;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName: FieldDemo
 * @Description:
 * @Date: 2020/9/11 22:14
 * *
 * @author: achao<achao1441470436 @ gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
public class FieldDemo {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchFieldException {
        Field field = UserInfo.class.getDeclaredField("serialVersionUID");
        BeanFieldSort.BeanFieldSorts annotation = field.getAnnotation(BeanFieldSort.BeanFieldSorts.class);
        for (BeanFieldSort beanFieldSort : annotation.value()) {
            System.out.println(beanFieldSort.order());
        }
        BeanFieldSort empty = field.getAnnotation(BeanFieldSort.class);
        System.out.println("---");
        System.out.println(Objects.isNull(empty));
//        empty.order();        NPE
    }

    private static void old() throws InstantiationException, IllegalAccessException {
        //获取对象
        Class<UserInfo> userInfoClass = UserInfo.class;
        //创建对象
        UserInfo userInfo = userInfoClass.newInstance();
        System.out.println(userInfo);
        //获取bean中所有字段
        Field[] fields = userInfoClass.getDeclaredFields();
        //遍历
        for (Field field : fields) {
            //把private属性设为可修改
            field.setAccessible(true);
            field.set(userInfo, "yeah!");
            System.out.println(field.getName());
        }
        System.out.println("------------");
        //排序
        List<Field> fieldList = Arrays
                .stream(fields)
                .sorted(Comparator.comparingInt(f -> f
                        .getAnnotation(BeanFieldSort.class).order()))
                .collect(Collectors.toList());
        //遍历输出结果
        fieldList.stream().map(Field::getName).forEach(System.out::println);
        System.out.println(userInfo);
    }
}
